package scau.mis4.chanyulin.tools;

import java.net.InetAddress;

/**
 * Created by cyl on 2017/12/18.
 * 判断网络是否畅通
 */
public class NetworkChecker implements Runnable {

    private String targetURL;
    private boolean networkAvailable;
    private int timeout = 2500;

    public NetworkChecker(String targetURL, int timeout, double period) {
        this.targetURL = targetURL;
        this.timeout = timeout;
        PeriodTask.createAndSchedule(this, period);
    }

    public NetworkChecker(String targetURL, int timeout) {
        this.targetURL = targetURL;
        this.timeout = timeout;
        PeriodTask.createAndSchedule(this, 10);
    }

    public NetworkChecker(String targetURL, double period) {
        this.targetURL = targetURL;
        PeriodTask.createAndSchedule(this, period);
    }

    public NetworkChecker(String targetURL) {
        this(targetURL, 10);
    }

    public String getTargetURL() {
        return targetURL;
    }

    public void setTargetURL(String targetURL) {
        this.targetURL = targetURL;
    }

    public boolean isNetworkAvailable() {
        return this.networkAvailable;
    }

    public void setNetworkAvailable(boolean networkAvailable) {
        this.networkAvailable = networkAvailable;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    @Override
    public void run() {
        try {
            InetAddress inetAddress = InetAddress.getByName(targetURL);
            this.networkAvailable = inetAddress.isReachable(timeout);
            if (!networkAvailable) System.out.println("[网络连接检查] 异常：" + this.targetURL);
        } catch (Exception e) {
            this.networkAvailable = false;
            System.out.println("[网络连接检查] 异常：" + this.targetURL);
        }
    }

}